// export let httpUrl = 'http://127.0.0.1:8010'  // 接访问地址
export let httpUrl = 'https://ax-admin.dearweb.cn/api'  // 接访问地址

import { getStorageData, removeStorageData } from "@/utils/storageData.js"

export function get(url, data) {
  console.log(data, 123)
  url = url + '?'
  let promise = new Promise((resolve, reject) => {
    uni.request({
      url: httpUrl + url,
      method: 'GET',
      data,
      header: {
        'Authorization': getStorageData('token')
      },
      success: function (res) {
        if (res.data) {
          if (res.data.code == 1001) {
            throwFuc(res.data)
            if (res.data.message == '登录失效~') {
              uni.clearStorage();
              uni.navigateTo({
                url: '/pages/login/index'
              })
            }
            resolve(res.data)
          }
          if (res.data.code == 1000 || res.data.status == 200) {
            resolve(res.data)
          } else {

            reject(res.data)
          }
        } else {
          reject(res.data)
        }
      },
      fail: (err) => {
        if (res.data.code == 1001) {
          throwFuc(res.data)
          resolve(res.data)
        }
        reject(err)
      }
    })
  })
  return promise
}

export function post(url, data, isParams) {
  // post方法需要使用 query 传参
  if (isParams) {
    let _url = ""
    for (let item in data) {
      _url += item + '=' + data[item]
    }
    url += ('?' + _url)
  }
  let promise = new Promise((resolve, reject) => {
    uni.request({
      url: httpUrl + url,
      data,
      method: 'POST',
      dataType: 'json',
      header: {
        'content-type': 'application/json',
        'Authorization': getStorageData('token')
      },
      success: function (res) {
        if (res.data.code == 1001) {
          throwFuc(res.data)
          if (res.data.message == '登录失效~') {
            uni.clearStorage();
            uni.navigateTo({
              url: '/pages/login/index'
            })
          }
          resolve(res.data)
        }
        if (res.data.code == 1000 || res.data.status == 200) {
          resolve(res.data)
        } else {
          if (res.data.code == 404) {
            res.msg = '网络地址错误'
          }
          if (res.data.code == 401) {
            res.msg = '请登录后操作'
            uni.navigateTo({
              url: '/pages/login/index'
            })
          }
          reject(res.data)
        }
      },
      fail: (err) => {
        if (res.data.code == 1001) {
          throwFuc(res.data)
          resolve(res.data)
        }
        reject(err)
      }
    })
  })
  return promise
}

const throwFuc = (data) => {
  let status = data.code
  let msg = data.message
  uni.showToast({
    title: msg,
    duration: 2000,
    icon: 'none'
  });
}